package com.example.caiyunappdevelopment.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.caiyunappdevelopment.R;

import java.util.ArrayList;

public class CityListAdapter extends RecyclerView.Adapter<CityListAdapter.ViewHolder> {

    public CityListAdapter(ArrayList<String> cities) {
        this.cities = cities;
    }

    private final ArrayList<String> cities;

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(
                LayoutInflater
                        .from(parent.getContext())
                        .inflate(R.layout.item_city_list, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.item0.setText(cities.get(3 * position));
        if (3 * position + 1 < cities.size()) {
            holder.item1.setVisibility(View.VISIBLE);
            holder.item1.setText(cities.get(3 * position + 1));
            if (3 * position + 2 < cities.size()) {
                holder.item2.setVisibility(View.VISIBLE);
                holder.item2.setText(cities.get(3 * position + 2));
            } else {
                holder.item2.setVisibility(View.GONE);
            }
        } else {
            holder.item1.setVisibility(View.GONE);
            holder.item2.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        if (cities.size() % 3 == 0)
            return cities.size() / 3;
        else
            return cities.size() / 3 + 1;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View view) {
            super(view);
        }

        final TextView item0 = itemView.findViewById(R.id.tv_city_item0);
        final TextView item1 = itemView.findViewById(R.id.tv_city_item1);
        final TextView item2 = itemView.findViewById(R.id.tv_city_item2);
    }

}
